<template>
  <div class="automatic-scrolling" ref="container">
    <div class="scroll-content" ref="content">
      <slot></slot>
    </div>
  </div>
</template>
<script>
/**
 * @description 自动滚动组件
 * step为步长,单位px,即每次滚动的距离,不接受小数
 * frequency为频率，单位ms,即滚动的间隔,每 frequency 滚动一次
 */
export default {
  name:'AutomaticScrolling',
  props:{
    step:{
      type:Number,
      default:1,
    },
    frequency:{
      type:Number,
      default:100
    }
  },
  data(){
    return{
      animationFrameId:null,
      lastTime:0
    }
  },
  watch:{
    step:"restartScrolling",
    frequency:"restartScrolling",
  },
  methods:{
    startScrolling(){
      const container=this.$refs.container;
      const content=this.$refs.content;
      if(!container||!content)return;
      this.lastTime=performance.now()
      const scroll=(timestamp)=>{
        if(!container)return
        const deltaTime=timestamp-this.lastTime
        if(deltaTime>=this.frequency){
          if(container.scrollTop+container.clientHeight>=container.scrollHeight){
            container.scrollTop=0
          }else {
            container.scrollTop+=this.step
          }
          this.lastTime=timestamp
        }
        this.animationFrameId=requestAnimationFrame(scroll)
      }
      this.animationFrameId=requestAnimationFrame(scroll)
    },
    stopScrolling(){
      if(this.animationFrameId){
        cancelAnimationFrame(this.animationFrameId)
        this.animationFrameId=null
      }
    },
    restartScrolling(){
      this.stopScrolling();
      this.startScrolling();
    }
  },
  beforeDestroy() {
    this.stopScrolling()
  },
  mounted() {
    this.startScrolling()
  }
}
</script>
<style lang="scss" scoped>
.automatic-scrolling{
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  .scroll-content{
    width: 100%;
    display: block;
  }
}
</style>
